import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Category, CategoryParam } from './model';

/**
 * 分页查询分类
 */
export async function pageCategories(params: CategoryParam) {
  const res = await request.get<ApiResult<PageResult<Category>>>(
    '/content/category/page',
    { params }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * Id查询
 * @param params
 * @returns
 */
export async function getCategory(id: number) {
  const res = await request.get<ApiResult<Category[]>>(
    '/content/category/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询列表
 */
export async function listCategories(params?: CategoryParam) {
  const res = await request.get<ApiResult<Category[]>>('/content/category', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加
 */
export async function addCategory(data: Category) {
  const res = await request.post<ApiResult<unknown>>('/content/category', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改
 */
export async function updateCategory(data: Category) {
  const res = await request.put<ApiResult<unknown>>('/content/category', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除
 */
export async function removeCategory(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    '/content/category/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
